/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.tb_waybill.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.persistence.PageNew;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.ToolsUtil;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.tb_car_info.entity.TbCarInfo;
import com.thinkgem.jeesite.modules.tb_car_info.service.TbCarInfoService;
import com.thinkgem.jeesite.modules.tb_cost.entity.TbCost;
import com.thinkgem.jeesite.modules.tb_cost.service.TbCostService;
import com.thinkgem.jeesite.modules.tb_discharge_cargo_address.entity.TbDischargeCargoAddress;
import com.thinkgem.jeesite.modules.tb_discharge_cargo_address.service.TbDischargeCargoAddressService;
import com.thinkgem.jeesite.modules.tb_driver.entity.TbDriver;
import com.thinkgem.jeesite.modules.tb_driver.service.TbDriverService;
import com.thinkgem.jeesite.modules.tb_fuel_consumption.entity.TbFuelConsumption;
import com.thinkgem.jeesite.modules.tb_fuel_consumption.service.TbFuelConsumptionService;
import com.thinkgem.jeesite.modules.tb_goods.entity.TbGoods;
import com.thinkgem.jeesite.modules.tb_goods.service.TbGoodsService;
import com.thinkgem.jeesite.modules.tb_goods_consignment_company.entity.TbGoodsConsignmentCompany;
import com.thinkgem.jeesite.modules.tb_goods_consignment_company.service.TbGoodsConsignmentCompanyService;
import com.thinkgem.jeesite.modules.tb_goods_receipt_company.entity.TbGoodsReceiptCompany;
import com.thinkgem.jeesite.modules.tb_goods_receipt_company.service.TbGoodsReceiptCompanyService;
import com.thinkgem.jeesite.modules.tb_loading_address.entity.TbLoadingAddress;
import com.thinkgem.jeesite.modules.tb_loading_address.service.TbLoadingAddressService;
import com.thinkgem.jeesite.modules.tb_waybill.entity.TbWaybill;
import com.thinkgem.jeesite.modules.tb_waybill.entity.TbWaybillDetail;
import com.thinkgem.jeesite.modules.tb_waybill.service.TbWaybillService;

/**
 * 运单管理Controller
 * @author ZhangYangZe
 * @version 2017-05-15
 */
@Controller
@RequestMapping(value = "${adminPath}/tb_waybill/tbWaybill")
public class TbWaybillController extends BaseController {

	@Autowired
	private TbWaybillService tbWaybillService;
	@Autowired
	private TbCarInfoService tbCarInfoService;
	@Autowired
	private TbDriverService tbDriverService;
	@Autowired
	private TbGoodsService tbGoodsService;
	@Autowired
	private TbLoadingAddressService tbLoadingAddressService;
	@Autowired
	private TbDischargeCargoAddressService tbDischargeCargoAddressService;
	@Autowired
	private TbGoodsConsignmentCompanyService tbGoodsConsignmentCompanyService;
	@Autowired
	private TbGoodsReceiptCompanyService tbGoodsReceiptCompanyService;
	@Autowired
	private TbFuelConsumptionService fuelConsumptionService;
	@Autowired
	private TbCostService costService;
	
	
	@ModelAttribute
	public TbWaybill get(@RequestParam(required=false) String id) {
		TbWaybill entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = tbWaybillService.get(id);
		}
		if (entity == null){
			entity = new TbWaybill();
		}
		return entity;
	}
	
	/**
	 * 运单列表
	 * @param tbWaybill
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("tb_waybill:tbWaybill:view")
	@RequestMapping(value = {"list", ""})
	public String list(TbWaybill tbWaybill, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<TbWaybill> page = tbWaybillService.findPage(new Page<TbWaybill>(request, response), tbWaybill); 
		model.addAttribute("page", page);
		return "modules/tb_waybill/tbWaybillList";
	}
	/**
	 * 运单添加页面
	 * @param tbWaybill
	 * @param model
	 * @return
	 */
	@RequiresPermissions("tb_waybill:tbWaybill:view")
	@RequestMapping(value = "form")
	public String form(TbWaybill tbWaybill, Model model) {
		TbCarInfo tbCarInfo = new TbCarInfo();
		tbCarInfo.setCarState(0);
		TbDriver tbDriver = new TbDriver();
		tbDriver.setDriverType("0");
		model.addAttribute("tbCarInfo", tbCarInfoService.findList(tbCarInfo));
		model.addAttribute("driver", tbDriverService.findList(tbDriver));
		model.addAttribute("goods", tbGoodsService.findList(new TbGoods()));
		model.addAttribute("loadingAddress", tbLoadingAddressService.findList(new TbLoadingAddress()));
		model.addAttribute("dischargeCargoAddress", tbDischargeCargoAddressService.findList(new TbDischargeCargoAddress()));
		model.addAttribute("goodsConsignmentCompany", tbGoodsConsignmentCompanyService.findList(new TbGoodsConsignmentCompany()));
		model.addAttribute("goodsReceiptCompany", tbGoodsReceiptCompanyService.findList(new TbGoodsReceiptCompany()));
		model.addAttribute("tbWaybill", tbWaybill);
		return "modules/tb_waybill/tbWaybillForm";
	}

	/**
	 * 创建/修改运单
	 * @param tbWaybill
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("tb_waybill:tbWaybill:edit")
	@RequestMapping(value = "save")
	public String save(TbWaybill tbWaybill, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, tbWaybill)){
			return form(tbWaybill, model);
		}
		tbWaybill.setWaybillNum(new Date().getTime()+"");
		tbWaybill.setState("0");
		tbWaybillService.save(tbWaybill);
		addMessage(redirectAttributes, "保存运单成功");
		return "redirect:"+Global.getAdminPath()+"/tb_waybill/tbWaybill/?repage";
	}
	
	@RequiresPermissions("tb_waybill:tbWaybill:edit")
	@RequestMapping(value = "saveNew")
	public String saveNew(TbWaybill tbWaybill, Model model, RedirectAttributes redirectAttributes) {
		tbWaybill.setWaybillNum(new Date().getTime()+"");
		tbWaybill.setState("0");
		if(tbWaybillService.tbWaybillDetailIsempty(tbWaybill.getTbWaybillDetailOne()) != null){
				Double weightOne = tbWaybill.getTbWaybillDetailOne().getWeight();    //获取货物运输1的货物重量
				Double unitPriceOne = tbWaybill.getTbWaybillDetailOne().getUnitPrice();		//获取货物运输1的运价		
				TbWaybillDetail tbWaybillDetail = tbWaybill.getTbWaybillDetailOne(); //获取货物运输1的对象并赋值给新的货物运输
			if(tbWaybill.getTbWaybillDetailOne().getSettlement().equals("0")){
				tbWaybillDetail.setMoney(weightOne*unitPriceOne); //获取货物运输1的运费结算方式为：货物*运价
			}
			if(tbWaybill.getTbWaybillDetailOne().getSettlement().equals("1")){
				Double length=tbWaybill.getTbWaybillDetailOne().getLength();
				tbWaybillDetail.setMoney(weightOne*unitPriceOne*length);//获取货物运输1的运费结算方式为：货物*运价*运输里程
			}
			tbWaybill.setTbWaybillDetailOne(tbWaybillDetail);    //第一仓运输的货物
		}
		if(tbWaybillService.tbWaybillDetailIsempty(tbWaybill.getTbWaybillDetailTwo()) != null){
			Double weighttwo = tbWaybill.getTbWaybillDetailTwo().getWeight();   //获取货物运输2的货物重量
			Double unitPricetwo = tbWaybill.getTbWaybillDetailTwo().getUnitPrice();		//获取货物运输2的运价
			TbWaybillDetail tbWaybillDetailtwo = tbWaybill.getTbWaybillDetailTwo(); //获取货物运输2的对象
			if(tbWaybill.getTbWaybillDetailTwo().getSettlement().equals("0")){
			    tbWaybillDetailtwo.setMoney(weighttwo*unitPricetwo);//获取货物运输2的运费结算方式为：货物*运价
			}
			if(tbWaybill.getTbWaybillDetailTwo().getSettlement().equals("1")){
				Double lengthtwo=tbWaybill.getTbWaybillDetailTwo().getLength();
				tbWaybillDetailtwo.setMoney(weighttwo*unitPricetwo*lengthtwo);//获取货物运输2的运费结算方式为：货物*运价*运输里程
			}
			tbWaybill.setTbWaybillDetailTwo(tbWaybillDetailtwo);    //第二仓运输的货物
		}
		if(tbWaybillService.tbWaybillDetailIsempty(tbWaybill.getTbWaybillDetailThree()) != null){
			Double weightthree = tbWaybill.getTbWaybillDetailThree().getWeight();//获取货物运输3的货物重量
			Double unitPricethree = tbWaybill.getTbWaybillDetailThree().getUnitPrice();//获取货物运输3的运价
			TbWaybillDetail tbWaybillDetailthree = tbWaybill.getTbWaybillDetailThree();//获取货物运输3的对象
			if(tbWaybill.getTbWaybillDetailThree().getSettlement().equals("0")){
			    tbWaybillDetailthree.setMoney(weightthree*unitPricethree);//获取货物运输3的运费结算方式为：货物*运价
			}
			if(tbWaybill.getTbWaybillDetailTwo().getSettlement().equals("1")){
				Double lengththree=tbWaybill.getTbWaybillDetailThree().getLength();
				tbWaybillDetailthree.setMoney(weightthree*unitPricethree*lengththree);//获取货物运输2的运费结算方式为：货物*运价*运输里程
			}
			tbWaybill.setTbWaybillDetailThree(tbWaybillDetailthree);
		}
		tbWaybillService.saveNew(tbWaybill);
		addMessage(redirectAttributes, "保存运单成功");
		return "redirect:"+Global.getAdminPath()+"/tb_waybill/tbWaybill/?repage";
	}
	
	/**
	 * 删除
	 * @param tbWaybill
	 * @param redirectAttributes
	 * @return String
	 */
	@RequiresPermissions("tb_waybill:tbWaybill:edit")
	@RequestMapping(value = "delete")
	public String delete(TbWaybill tbWaybill, RedirectAttributes redirectAttributes) {
		tbWaybillService.delete(tbWaybill);
		addMessage(redirectAttributes, "删除运单成功");
		return "redirect:"+Global.getAdminPath()+"/tb_waybill/tbWaybill/?repage";
	}
	
	/**
	 * 等待调度的列表
	 * @param tbWaybill
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("tb_waybill:tbWaybill:view")
	@RequestMapping("dispatch/list")
	public String dispatchList(TbWaybill tbWaybill, HttpServletRequest request, HttpServletResponse response, Model model){		
		tbWaybill.setState("0");
		TbDriver tbDriver = new TbDriver();
		tbDriver.setDriverType("0");
		Page<TbWaybill> page = tbWaybillService.findPage(new Page<TbWaybill>(request,response),tbWaybill); 
		model.addAttribute("driver", tbDriverService.driverTypeOne(tbDriver));
		model.addAttribute("page", page);
		return "modules/tb_waybill/dispatchList";
	}
	
	@RequestMapping("dispatch/findDetailById")
	@ResponseBody
	protected TbWaybill findDetailById(@RequestParam("id")String id){
		TbWaybill tbWaybill = tbWaybillService.get(id);		
		return tbWaybill;
	}
	
	/**
	 * 调度
	 * @param id  订单id
	 * @param driver_id  司机id
	 * @return
	 */
	@RequiresPermissions("tb_waybill:tbWaybill:edit")
	@RequestMapping("dispatch/form")
	public String dispatchform(TbWaybill tbWaybill, Model model, RedirectAttributes redirectAttributes,HttpServletRequest request, HttpServletResponse response ){
		tbWaybillService.dispatchDriver(tbWaybill);
		addMessage(redirectAttributes, "指派司机成功");
		//return "redirect:"+Global.getAdminPath()+"/tb_waybill/tbWaybill/?repage";
		return dispatchList(new TbWaybill(), request, response, model);
	}
	
	/**
	 * 运输中审核列表
	 * @param tbWaybill
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("tb_waybill:auditInTransitList:view")
	@RequestMapping("auditInTransitList")
	public String auditInTransitList(TbWaybill tbWaybill, HttpServletRequest request, HttpServletResponse response, Model model){
		tbWaybill.setState("3");
		PageNew<TbWaybill> page = tbWaybillService.findPage(new PageNew<TbWaybill>(request, response), tbWaybill); 
		model.addAttribute("driver", tbDriverService.findList(new TbDriver()));
		model.addAttribute("page", page);
		return "modules/tb_waybill/audit_in_transit";
	}
	
	
	/**
	 * 运输中审核——审核
	 * @return
	 */
		@RequiresPermissions("tb_waybill:auditInTransitList:edit")
		@RequestMapping("auditInTransitEdit")
		public String auditInTransitEdit(HttpServletRequest request, HttpServletResponse response,@RequestParam("tbWaybillId") String waybillId,Model model){
			
			Map<String,Object> map = new HashMap<String, Object>();
			map.put("a", fuelConsumptionList(waybillId,"0"));
			map.put("b", fuelConsumptionList(waybillId,"1"));
			map.put("c", costList(waybillId,"0"));
			map.put("d", costList(waybillId,"1"));
			map.put("e", costList(waybillId,"2"));
			map.put("f", costList(waybillId,"3"));
			map.put("g", costList(waybillId,"4"));
			map.put("h", costList(waybillId,"5"));
			map.put("i", costList(waybillId,"6"));
			
			model.addAttribute("data", map);
			
			return "modules/tb_waybill/audit_in_transit_in";
		}
		/**
		 * 油品消耗列表
		 * @param id 运单ID
		 * @param type 0公司补油1加油站加油
		 * @return
		 */
		public List<Map<String,Object>> fuelConsumptionList(String id,String type){
			List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
			TbFuelConsumption tbFuelConsumption = new TbFuelConsumption();
			tbFuelConsumption.setWaybillId(id);
			//TODO 公司补油
			tbFuelConsumption.setType(type);
			List<TbFuelConsumption> list = fuelConsumptionService.findList(tbFuelConsumption);
			if(list != null && list.size()>0){
				for(int i=0;i<list.size();i++){
					Map<String,Object> m = new HashMap<String, Object>();					
					TbFuelConsumption t = list.get(i);					
					m.put("id", t.getId());
					m.put("waybillId", t.getWaybillId());
					m.put("driver", t.getTbDriverThree().getDriverName());
					m.put("goodName", t.getGoods().getGoodName());
					m.put("weight",t.getWeight() );
					m.put("unitPrice", t.getUnitPrice());
					m.put("money", t.getMoney());
					m.put("dateTime",t.getDateTime() );
					m.put("bigPhoto", ToolsUtil.strToStrArray(t.getBigPhoto()));
					m.put("smallPhoto", ToolsUtil.strToStrArray(t.getSmallPhoto()));
					m.put("remarks", t.getRemarks());
					m.put("creatTime",t.getCreateDate() );					
					result.add(m);
				}
			}
			return result ;
		}
		/**
		 * 运输总审核费用列表
		 * @param id 运单id
		 * @param type0配件费1维修费2过路费3协调费4住宿费5保养费6其他
		 * @return
		 */
		public List<Map<String,Object>> costList(String id,String type){
			List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
			TbCost cost = new TbCost();
			cost.setWaybillId(id);
			cost.setType(type);
			List<TbCost> list = costService.findList(cost);
			if(list != null && list.size()>0){
				for(int i=0;i<list.size();i++){
					Map<String,Object> m = new HashMap<String, Object>();
					TbCost c = list.get(i);
					m.put("id",c.getId());
					m.put("waybillId", c.getWaybillId());
					m.put("parst",c.getParst());
					m.put("price", c.getPrice());
					m.put("number",c.getNumber());
					m.put("money", c.getMoney());
					m.put("datetime", c.getDateTime());
					m.put("remarks", c.getRemarks());
					m.put("createDate",c.getCreateDate());
					m.put("photoBig", ToolsUtil.strToStrArray(c.getPhotoBig()));
					m.put("photoSmall", ToolsUtil.strToStrArray(c.getPhotoSmall()));
					result.add(m);
				}
			}
			return result ;
		}
		/**
		 * 运输中审核——完善页
		 * @param type
		 * @param id
		 * @param request
		 * @param response
		 * @param model
		 * @return
		 */
		@RequiresPermissions("tb_waybill:auditInTransitList:view")
		@RequestMapping("runningPassForm")
		public String runningPassForm(TbWaybill waybill,HttpServletRequest request, HttpServletResponse response,Model model){
			try{
				
				Integer key = Integer.parseInt(waybill.getClassType());
				switch (key) {
				case 0:
					TbFuelConsumption tbFuelConsumption = fuelConsumptionService.get(waybill.getGet_id());
					waybill.setFuelConsumption(tbFuelConsumption);
					waybill.setClassType("0");
					break;
				case 1:
					TbCost cost = costService.get(waybill.getGet_id());
					waybill.setCost(cost);
					waybill.setClassType("1");
					break;
				default:
					break;
				}
				model.addAttribute("waybill", waybill);
				model.addAttribute("goods", tbGoodsService.findList(new TbGoods()));;
			}catch(Exception e){
				e.printStackTrace();
			}
			return "modules/tb_waybill/running_pass"; 
		}
		/**
		 * 运输中审核通过
		 * @param request
		 * @param response
		 * @param waybillId
		 * @param model
		 * @return
		 */
		@RequiresPermissions("tb_waybill:auditInTransitList:edit")
		@RequestMapping("runningPass")
		public String runningPass(HttpServletRequest request, HttpServletResponse response,TbWaybill tbWaybill,Model model){
			Integer key = ToolsUtil.strToInt(tbWaybill.getClassType());
			switch (key) {
			case 0:
				tbWaybill.getFuelConsumption().setState("1");
				tbWaybillService.runningFallOrPass(0, tbWaybill.getFuelConsumption(), null);
				break;
			case 1:
				tbWaybill.getCost().setState("1");
				tbWaybillService.runningFallOrPass(1, null, tbWaybill.getCost());
				break;
			default:
				break;
			}
			
			
			return "";
		}
		/**
		 * 运输中审核不通过
		 * @param request
		 * @param response
		 * @param waybillId
		 * @param model
		 * @return
		 */
		@RequiresPermissions("tb_waybill:auditInTransitList:edit")
		@RequestMapping("runningFall")
		public String runningFall(HttpServletRequest request, HttpServletResponse response,TbWaybill tbWaybill,String id,Model model){
			Integer key =  ToolsUtil.strToInt(tbWaybill.getClassType());
			switch (key) {
			case 0:
				TbFuelConsumption fuelConsumption = new TbFuelConsumption();
				fuelConsumption.setId(tbWaybill.getId());
				fuelConsumption.setState("2");
				fuelConsumption.setFallContext(tbWaybill.getCost().getFallContext());
				tbWaybillService.runningFallOrPass(key, fuelConsumption, null);
				break;
			case 1:
				tbWaybill.getCost().setState("2");
				
				tbWaybillService.runningFallOrPass(key, null, tbWaybill.getCost());
				break;
			default:
				break;
			}
			
			
			return auditInTransitEdit(request, response, tbWaybill.getId(), model);
		}
		
}